import formInfo from '@ohos.app.form.formInfo';
import formBindingData from '@ohos.app.form.formBindingData';
import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility';
import formProvider from '@ohos.app.form.formProvider';
import relationalStore from '@ohos.data.relationalStore';
import { MyDate } from '../pages/MyDate';
import { Schedule } from '../pages/Schedule';
import { MyTime } from '../pages/MyTime';

export default class EntryFormAbility extends FormExtensionAbility {

  onAddForm(want) {
    // Called to return a FormBindingData object.
    const formId = want.parameters["ohos.extra.param.key.form_identity"];
    let formData = {
      formId: formId,
      title: '',
      start: '',
      end: '',
      color: '',
    };
    return formBindingData.createFormBindingData(formData);
  }

  onCastToNormalForm(formId) {
    // Called when the form provider is notified that a temporary form is successfully
    // converted to a normal form.
  }

  onUpdateForm(formId) {
    // Called to notify the form provider to update a specified form.
    const STORE_CONFIG = {
      name: 'SchedulesRdb.db',
      securityLevel: relationalStore.SecurityLevel.S1
    };
    relationalStore.getRdbStore(this.context, STORE_CONFIG, (err, store) => {
      const predicates = new relationalStore.RdbPredicates('SCHEDULES')
      predicates
        .equalTo('DATE', MyDate.today())
        .greaterThan('END', MyTime.now())
        .orderByAsc('END')
      store.query(predicates)
        .then((rs:relationalStore.ResultSet)=> {
          let obj = {
            title: '',
            start: '',
            end: '',
            color: '',
          }
          if (rs.goToNextRow()) {
            obj = {
              title:rs.getString(rs.getColumnIndex('TITLE')),
              start:rs.getString(rs.getColumnIndex('START')),
              end:rs.getString(rs.getColumnIndex('END')),
              color:rs.getString(rs.getColumnIndex('COLOR'))
            }
          }
          let formData = formBindingData.createFormBindingData(obj);
          formProvider.updateForm(formId, formData)
        })
    })
  }

  onChangeFormVisibility(newStatus) {
    // Called when the form provider receives form events from the system.
  }

  onFormEvent(formId, message) {
    // Called when a specified message event defined by the form provider is triggered.
    this.onUpdateForm(formId)
  }

  onRemoveForm(formId) {
    // Called to notify the form provider that a specified form has been destroyed.
  }

  onAcquireFormState(want) {
    // Called to return a {@link FormState} object.
    return formInfo.FormState.READY;
  }
};